package com.example.poemtest.index.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.poemtest.Activity.BottomNavigationViewActivity;
import com.example.poemtest.R;
import com.example.poemtest.index.util.ExoPlayerManger;
import com.example.poemtest.index.util.MyClickListener;
import com.example.poemtest.utils.FullScreenUtil;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;

/**
 * 诗词大会视频的视频播放页面
 */
public class PoetryVideoDetailActivity extends AppCompatActivity implements MyClickListener.MyClickCallBack {

    public PlayerView playerView;
    private ExoPlayerManger exoPlayerManger;
    private Context context = PoetryVideoDetailActivity.this;
    private ImageView imageFullScreen;
    //是否全屏
    private Boolean isFullScreen = true;
    //是否隐藏进度条和控制按钮
    private Boolean isHide = false;
    private ImageView ivBack;
    //是否正在播放
    private boolean isPlaying = true;
    private TextView videoName, videoDesc, sportZhishi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FullScreenUtil.getInstance().fullScreen(this,true);
        requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题 //这行代码一定要在setContentView之前，不然会闪退
        setContentView(R.layout.activity_poetry_video_detail);
        setContentView(R.layout.activity_poetry_video_detail);

        //接收传过来的视频信息
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String video_name = bundle.getString("video_name","nothing");
        String video = bundle.getString("video_src");
        Log.e("video",video);
        initview(video, video_name);

        imageFullScreen = findViewById(R.id.exo_fullscreen);
        imageFullScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int flagsFullScreen = WindowManager.LayoutParams.FLAG_FULLSCREEN;
                if(isFullScreen) {
                    toggleFullscreen();
//                    getWindow().addFlags(flagsFullScreen); // 设置全屏
                    //如果上面的不起作用，可以换成下面的。
//                    if (getSupportActionBar()!=null) getSupportActionBar().hide();    //应用标题栏
//                    isFullScreen = false;
                }else { //退出全屏
                    toggleFullscreen();
                    WindowManager.LayoutParams attrs = getWindow().getAttributes();
                    attrs.flags &= (~flagsFullScreen);
                    getWindow().setAttributes(attrs);
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                    if (getSupportActionBar()!=null) getSupportActionBar().show();    //应用标题栏
                    isFullScreen = true;
                }
            }
        });

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFullScreen) {
                    //当前是全屏模式，点击缩小
                    toggleFullscreen();
                } else {
                    //如果不是全屏模式，点击返回视频页面
                    Intent intent = new Intent(PoetryVideoDetailActivity.this, PoetryVideoActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    //    视频放大缩小方法
    private void toggleFullscreen() {
        if (isFullScreen) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
//            getSupportActionBar().show();
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
//            getSupportActionBar().hide();
        }
        isFullScreen = !isFullScreen;
    }

    /**
     * 开始和暂停播放视频
     * @param playWhenReady
     */
    private void setPlayWhenReady(boolean playWhenReady) {
        SimpleExoPlayer simpleExoPlayer = exoPlayerManger.create();
        //设置音量
        simpleExoPlayer.setVolume(10);
        simpleExoPlayer.setVolume(0);
//        simpleExoPlayer.setRepeatMode(1);

        playerView.setPlayer(simpleExoPlayer);
        //监听（可自定义拓展）
//        simpleExoPlayer.addListener(this);
        //开启播放
        simpleExoPlayer.setPlayWhenReady(playWhenReady);
    }

    //暂停和恢复函数
    private void togglePlay() {
        if (isPlaying) {
            setPlayWhenReady(false);
        } else {
            setPlayWhenReady(true);
        }
        isPlaying = !isPlaying;
    }


    //    以下是生命周期
    @Override
    protected void onStart() {
        super.onStart();
        playerView.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        playerView.onPause();
    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        player.release();
//    }

    /**
     * 单击屏幕，隐藏或显示进度条和控制按钮
     */
    @Override
    public void oneClick() {
//        Toast.makeText(this, "单击", Toast.LENGTH_SHORT).show();
        if (!isHide) {
            playerView.hideController();
            isHide = true;
        }
    }

    /**
     * 双击屏幕，暂停或者继续播放
     */
    @Override
    public void doubleClick() {
//        Toast.makeText(this, "双击", Toast.LENGTH_SHORT).show();
        //设置视频的暂停和继续
        togglePlay();
    }

    //注意：在使用ExoP注意：在使用ExoPlayer时，需要在Activity中保持屏幕常亮以避免视频播放过程中屏幕自动关闭。layer时，需要在Activity中保持屏幕常亮以避免视频播放过程中屏幕自动关闭。
    @Override
    protected void onResume() {
        super.onResume();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onPause() {
        super.onPause();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void initview(String playVideoUrl, String video_name){
        playerView = findViewById(R.id.poetry_video_view);
        playerView.setOnTouchListener(new MyClickListener(this));
        exoPlayerManger = new ExoPlayerManger();
        exoPlayerManger.setBuilderContext(this);
        ivBack = findViewById(R.id.iv_back);
        //设置Uri
        exoPlayerManger.setVideoUrl(playVideoUrl);
//        exoPlayerManger.setVideoUrl("https://tv.cctv.com/2023/01/25/VIDEdTbRVF51R6Q3snSAJTI3230125.shtml");
        //设置从raw下读取的文件路径
//        exoPlayerManger.setVideoUrl(RawResourceDataSource.buildRawResourceUri(video).toString());
        setPlayWhenReady(true);
    }
}